<script lang="ts">
import {defineComponent} from 'vue'
import DialogAndBlock from "@/components/DialogAndBlock/index.vue";
import DynamicForm from "@/components/DynamicForm3/index.vue";
import {FormConfigItem} from "@/components/DynamicForm3/types";
import {useDict} from "@/utils/dict";
import SelectBasePath from "@/components/SelectBasePath/index.vue";
import {downloadReq} from "@/api/download";
import {ElMessage, ElMessageBox} from "element-plus";
import EditDirMixin from "@/mixins/editDirMixin";
import DynamicTable from "@/components/DynamicTable3/index.vue";
import {TableConfigItem} from "@/components/DynamicTable3/types";
import PageContent from "@/components/pageContent.vue";

export default defineComponent({
  name: "AddTask",
  components: {PageContent, DynamicTable, SelectBasePath, DynamicForm, DialogAndBlock},
  data(){
    return {
      loading: false,
      copyTaskId: '',
      params: {},
      formData: {},
      formConfigList: [
        {
          type: 'input',
          label: '任务名称',
          prop: 'downloadName',
          props: {
            clearable: true,
          },
        },
        {
          type: 'select',
          label: '任务类型',
          prop: 'downloadType',
          props: {
            options: [],
            clearable: true,
          },
        },
      ] as FormConfigItem[],
      downloadTaskInfo: [],
      timer: null,
      tableConfgList: [
        {
          label: '下载的url',
          prop: 'downloadUrl'
        },
        {
          label: '下载的名字',
          prop: 'downloadName'
        },
        {
          label: '下载的页面url',
          prop: 'downloadPageUrl'
        },
        {
          label: '下载进度',
          prop: 'downloadPer'
        },
      ] as TableConfigItem[],
      watchDownloadTypeClearData: true,
    }
  },
  watch: {
    'formData.downloadType': {
      async handler(value:string) {
        this.formConfigList.splice(2,this.formConfigList.length - 2)
        await this.$nextTick()
        if(this.watchDownloadTypeClearData) {
          Object.keys(this.formData).forEach(key=>{
            if(!this.formConfigList.find(i=>i.prop === key)) {
              delete this.formData[key]
            }
          })
        }
        await this.$nextTick()
        const find1 = this.formConfigList.find(i=>i.prop === 'downloadType')
        const options = find1.props.options
        const find = options.find(i=>i.value === value)
        if(!find) {
          return
        }
        find.downloadParams.forEach(i=>{
          const item = {
            ...i,
            props: {
              ...i.props,
              clearable: true,
            },
          } as FormConfigItem
          if(i.type === 'SelectBasePath') {
            item.slotName = 'SelectBasePath'
            item.type='slot'
            item.slotInitValue=(formData, item)=>{
              return '/'
            }
          }
          if(i.type === 'downloadInstructions') {
            item.slotName = 'downloadInstructions'
            item.type='slot'
            item.slotInitValue=(formData, item)=>{
              return ''
            }
          }
          // 给值进行初始化
          if(item.initValue) {
            this.formData[item.prop] = item.initValue
          }
          this.formConfigList.push(item)
        })
        if(this.isLookDir) {
          this.formConfigList.push({
            prop: 'downloadStatus',
            type: 'input',
            label: '下载状态'
          })
          this.formConfigList.push({
            prop: 'downloadTaskId',
            type: 'input',
            label: '任务id'
          })
        }
      }
    }
  },
  created() {
    useDict('getDownloadListType',({getDownloadListType})=>{
      const find = this.formConfigList.find(i=>i.prop === 'downloadType')
      find.props.options = getDownloadListType
    })
  },
  emits:['success'],
  mixins: [EditDirMixin],
  methods: {
    open(params) {
      this.params = params
      this.edirDir = params.edit
      if(!this.isAddDir) {
        const run = ()=>{
          this.watchDownloadTypeClearData = false
          return downloadReq.getDownloadDetails(this.params.row.downloadTaskId).then(res=>{
            if(res.data.downloadTask) {
              this.formData = {
                ...res.data.downloadTask,
                ...JSON.parse(res.data.downloadTask.downloadParams),
              }
              delete this.formData.downloadParams
              this.downloadTaskInfo = res.data.downloadTaskInfo || []
            } else {
              clearInterval(this.timer)
              this.timer = null
            }
          }).finally(()=>{
            this.$nextTick(()=>{
              this.watchDownloadTypeClearData=true
            })
          })
        }
        this.timer = setInterval(()=>{
          run()
        },3000)
        this.loading=true
        run().finally(()=>{
          this.loading=false
        })
      }
      this.$refs.dialogRef.open()
    },
    closed() {
      clearInterval(this.timer)
      this.timer= null
      this.$refs.DynamicFormRef.resetFields()
      this.downloadTaskInfo = []
      this.$emit('success')
    },
    submit() {
      if(!this.formData.downloadType) {
        ElMessage.error("下载类型不能为空")
        return
      }
      if(!this.formData.downloadName) {
        ElMessage.error("下载名称不能为空")
        return
      }
      let find = this.formConfigList.find(i=>i.type === 'SelectBasePath')
      if(find && !this.formData[find.prop]) {
        this.formData[find.prop] = find.slotInitValue(this.formData,find)
      }
      ElMessageBox.confirm("是否提交","提示").then(()=>{
        delete this.formData.downloadParams
        downloadReq.submitDownload(this.formData).then(res=>{
          ElMessage.success(res.data as string)
          this.$emit('success')
          this.$refs.dialogRef.close()
        })
      })
    },
    searchTask() {
      if(!this.copyTaskId) {
        ElMessage.error('任务id不能为空')
        return
      }
      this.watchDownloadTypeClearData = false
      this.loading=true
      downloadReq.getDownloadDetails(this.copyTaskId).then(res=>{
        if(res.data.downloadTask) {
          delete res.data.downloadTask.downloadStatus
          delete res.data.downloadTask.downloadTaskId
          delete res.data.downloadTask.userId
          this.formData = {
            ...res.data.downloadTask,
            ...JSON.parse(res.data.downloadTask.downloadParams),
          }
          delete this.formData.downloadParams
        } else {
          ElMessage.error('任务不存在')
        }
      }).finally(()=>{
        this.$nextTick(()=>{
          this.watchDownloadTypeClearData=true
        })
        this.loading=false
      })
    },
    deleteTheOriginalTask() {
      ElMessageBox.confirm("是否删除","提示").then(()=>{
        downloadReq.delDownload(this.copyTaskId).then((res)=>{
          ElMessage.success(res.data as string)
          this.$emit('success')
          this.copyTaskId = ""
        })
      })
    },
    urlParsing() {
      ElMessageBox.confirm("是否进行url解析","提示").then(res=>{
        downloadReq.urlParsing(this.formData).then(res=>{
          this.formData = Object.assign(this.formData,res.data)
        })
      })
    }
  }
})
</script>

<template>
  <DialogAndBlock
    ref="dialogRef"
    :title="edirDir.label+'任务'"
    @closed="closed"
    content-overflow="auto"
  >
    <PageContent>
      <div v-loading="loading">
        <div v-if="isAddDir" style="margin-bottom: 20px">
          <el-input
            v-model="copyTaskId"
            placeholder="复制任务id"
          >
            <template #prepend>复制任务的id</template>
            <template #append>
              <el-button icon="Search"
                         @click="searchTask"
              />
            </template>
          </el-input>
        </div>
        <div>
          <DynamicForm
            v-model="formData"
            :form-config-list="formConfigList"
            :created-init-value="false"
            :span="24"
            ref="DynamicFormRef"
            slot-name-first
            :disabled="!isAddDir"
          >
            <template #SelectBasePath="{item}">
              <SelectBasePath
                :disabled="!isAddDir"
                v-model="formData[item.prop]"
              ></SelectBasePath>
            </template>
            <template #downloadInstructions="{item}">
              <el-input
                :model-value="item.value"
                autosize
                readonly
                type="textarea"
              />
            </template>
          </DynamicForm>
        </div>
        <div v-if="!isAddDir">
          <DynamicTable
            :data="downloadTaskInfo"
            :created-init-value="false"
            :table-config-list="tableConfgList"
          ></DynamicTable>
        </div>
        <div class="btns">
          <el-button
            type="danger"
            @click="deleteTheOriginalTask"
            v-if="copyTaskId && isAddDir"
          >
            删除原任务
          </el-button>
          <el-button
            type="info"
            @click="urlParsing"
            v-if="formData.downloadType && isAddDir"
          >
            url解析
          </el-button>
          <el-button
            type="primary"
            @click="submit"
            v-if="isAddDir"
          >
            提交
          </el-button>
        </div>
      </div>
    </PageContent>
  </DialogAndBlock>
</template>

<style scoped lang="scss">
.pageContent{
  width: auto;
  max-height: 70vh;
}
.btns{
  text-align: right;
}
</style>
